# coding=utf-8

import urllib
import urllib.request
import http.cookiejar
import simplejson
import configparser
import sys
import requests



def text_wrapped_by(start, end ,content):
    si = content.find(start)
    if si != -1:
        si += len(start)
    ei = content.find(end, si)
    if ei != -1:
        return content[si:ei]
    return None


class BaiduUser(object):

    COOKIE_PATH = "cookies"

    LOGIN_URL = "http://passport.baidu.com/?login"
    LOGIN_IMG_URL = "http://passport.baidu.com/?verifypic"
    POST_URL = "http://tieba.baidu.com/f/commit/thread/add"
    THREAD_URL = "http://tieba.baidu.com/f/commit.thread/add"
    TBS_URL = "http://tieba.baidu.com/dc/common/tbs"
    VCODE_URL = "http://tieba.baidu.com/f/user/json_vocde? lm=%s&rs10=2&rs1=0&t=0.7"
    IMG_URL = "http://tieba.baidu.com/cgi-bin/genimg?%s"

    POST_ERR_MSGS = {
    "38": "验证码超时，请重新输入",
    "40": "验证码输入错误，请您返回后重新输入",
    "703": "为了减少恶意灌水和广告贴，本吧被设置为仅本吧会员才能发帖",
    "704": "为了减少恶意灌水和广告贴，本吧被设置为仅本吧管理团队才能发帖，给您带来的不便表歉意",
    "705": "本吧当前只能浏览，不能发帖！",
    "706": "抱歉，本帖暂时无法回复。",
    "900": "为抵御挖坟威海，本吧吧主已放出贴吧神兽--超级静止蛙，本帖暂时无法回复。",
    }

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.cj = http.cookiejar.MozillaCookieJar('cookie.txt')
        self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj))
        self.opener.addheaders = [("User-agent", "Mozilla/5.0 (x11; U; FreeBSD i386; en-US; rv:1.9.1) Gecko/20090704 Firefox/3.5"), ("Accept", "*/*")]
        cf = configparser.ConfigParser()
        cf.read("config.ini")
        cookie = cf.get("cookie", "cookie")
        self.cookdic = dict(Cookie=cookie)

    def is_login(self):
        try:
            req = requests.get(self.TBS_URL, cookies=self.cookdic, timeout=100)
            print(req.text)
        except:
            return None
        if req.status_code != 200:
            print("haven't get 200, status_code is: " + str(req.status_code))
            sys.exit(-1)
        content = simplejson.loads(req.text)
        self.tbs = content["tbs"]
        return content["is_login"]

    def login(self, verify_code=""):
        if self.is_login():
            print("登陆成功")
            return
        print("登录失败")
        return

    def post(self, url, title, content):
        print(u"%s 正在发表主帖(%s)..." % (self.username, url))
        return self._post("thread", url, title, content)

    def _post(self, ptype, *args):
        url=''
        title = ''
        conteng = ''
        if ptype == "thread":
            url, title, content = args
        else:
            url, content = args
        # 先请求下整个页面，求一些参数？

        post_content = requests.get(url, cookies=self.cookdic,timeout=100).text
        print(post_content)
        tieba_name = self.get_tieba_name(post_content)
        if not tieba_name:
            return
        tieba_name = tieba_name.encode("utf-8")
       # tbs = self.get_tbs(post_content)
        tid = self.get_tid(post_content)
        fid = self.get_fid(post_content)
        #vcode_md5 = self.get_vcode(fid)

        # 获得验证码而且写入本地文件
        #vcode = self.open_img(self.IMG_URL % vcode_md5)

        post_args = {
            "ie": "utf-8",
            "kw": "残9527",
            "fid": fid,
            #"tid": 0,
            # "vcode_md5": vcode_md5,
            "floor_num": "",
            "rich_text": 1,
            "tbs": self.tbs,
            "content": content,
            #"basilisk": 1,
            #"hasuploadpic": 0,

           # "picsign": "",
           # "tfrom": 1,
           # "quote_id": 0,
           # "user_type": 0,

            #"vcode": vcode,
            }
        if ptype == "thread":
            post_args.update(
            title=title,
            floor_num=0,
            __type__="thread"
            )

        print("请求前的参数：=====")
        print(post_args)

        ret = requests.post(self.POST_URL, cookies=self.cookdic, timeout=100,data=post_args)
        print(ret.text)
        ret = simplejson.loads(ret.text)
        ret_no = ret["no"]
        if ret_no == 0:
            print("发帖成功！(%s)..." % url)
            return
        err_msg = self.POST_ERR_MSGS.get(str(ret_no))
        if err_msg:
            print(err_msg)
        else:
            print("发帖失败。(%s)..." % ret_no)
        if ret_no in (38, 40):
            return self._post(ptype, *args)

    @staticmethod
    def get_tieba_name(content):
        ret = text_wrapped_by("<title>", u"-百度贴吧", content)
        if ret:
            return ret.split("_")[-1]
        return None

    @staticmethod
    def get_tid(content):
        ret = text_wrapped_by("tid:'", "'", content)
        return ret\


    @staticmethod
    def get_tbs(content):
        ret = text_wrapped_by("tbs:'", "'", content)
        return ret

    @staticmethod
    def get_fid(content):
        ret = text_wrapped_by("PageData.forum", "}", content)
        ret = text_wrapped_by("'id':", ',', ret)
        print(ret)
        return ret

if __name__ == '__main__':
    username = "微笑的小小刀"
    password = "111111"
    u = BaiduUser(username, password)
    u.login()
    tieba_name = "残9527"
    tiebaUrl = "http://tieba.baidu.com/f?kw=%s" %tieba_name
    u.post(tiebaUrl, "新人求助", "求助贴，请各位大神帮忙")
